import 'package:flutter/material.dart';
import 'package:flutter_ui/common/app_theme.dart';

/// 筛选对话框组件
///
/// 用于显示患者筛选选项的弹出对话框，包含院区筛选和级别筛选
/// 支持弹性动画效果，优化用户体验
class FilterDialog extends StatefulWidget {
  /// 对话框关闭回调
  final VoidCallback onClose;

  /// 确认按钮回调
  final VoidCallback onConfirm;

  /// 构造函数
  const FilterDialog({
    super.key,
    required this.onClose,
    required this.onConfirm,
  });

  @override
  State<FilterDialog> createState() => _FilterDialogState();
}

class _FilterDialogState extends State<FilterDialog>
    with SingleTickerProviderStateMixin {
  // 动画控制器
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<double> _opacityAnimation;

  // 选中状态管理
  // 院区筛选（单选）
  String _selectedHospitalFilter = '今入院/入科';
  final List<String> _hospitalFilterOptions = ['今入院/入科', '母婴同床', '特殊关注'];

  // 级别筛选（多选）
  final Map<String, bool> _levelFilterSelections = {
    'I 级护理': false,
    'II 级护理': false,
    'III 级护理': false,
    '手术病人': false,
    '病重病人': false,
    '高危病人': false,
    '高危DVT': false,
    '压疮病人': false,
    '护理路径': false,
    'VTE评分': false,
    '欠费': false,
  };

  // 筛选选项颜色映射
  final Map<String, Color> _filterColors = {
    'I 级护理': const Color(0xFF1976D2),
    'II 级护理': const Color(0xFFF57C00),
    'III 级护理': const Color(0xFFD32F2F),
    '手术病人': const Color(0xFFE67E22),
    '病重病人': const Color(0xFFFF7043),
    '高危病人': const Color(0xFFE53935),
    '高危DVT': const Color(0xFFD81B60),
    '压疮病人': const Color(0xFF8E24AA),
    '护理路径': const Color(0xFF1E88E5),
    'VTE评分': const Color(0xFF00BCD4),
    '欠费': const Color(0xFFFF5722),
    '今入院/入科': const Color(0xFF2196F3),
    '母婴同床': const Color(0xFF2196F3),
    '特殊关注': const Color(0xFF2196F3),
  };

  @override
  void initState() {
    super.initState();

    // 初始化动画控制器
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    // 偏移量动画，从顶部 (-1.0) 到原始位置 (0.0)
    _offsetAnimation = Tween<Offset>(
      begin: const Offset(0.0, -1.0), // 初始位置在顶部
      end: Offset.zero, // 最终位置在原始位置
    ).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeOutBack, // 使用弹性曲线
      ),
    );

    // 透明度动画，从0.0到1.0
    _opacityAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeIn),
    );

    // 启动动画
    _animationController.forward();
  }

  // 声明偏移量动画
  late Animation<Offset> _offsetAnimation;

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  /// 关闭对话框
  void _closeDialog() {
    // 反向播放动画
    _animationController.reverse().then((_) {
      widget.onClose();
    });
  }

  /// 确认选择
  void _confirmSelection() {
    // 反向播放动画
    _animationController.reverse().then((_) {
      widget.onConfirm();
    });
  }

  /// 切换筛选选项状态
  void _toggleLevelFilterOption(String option) {
    setState(() {
      _levelFilterSelections[option] =
          !(_levelFilterSelections[option] ?? false);
    });
  }

  /// 选择院区筛选选项（单选）
  void _selectHospitalFilter(String option) {
    setState(() {
      _selectedHospitalFilter = option;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      // 点击背景不关闭对话框，只能通过按钮关闭
      onTap: () {},
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return Container(
            color: Colors.black.withOpacity(0.5 * _opacityAnimation.value),
            width: double.infinity,
            height: double.infinity,
            child: Column(
              children: [
                SlideTransition(
                  position: _offsetAnimation, // 应用偏移量动画
                  child: Container(
                    width: double.infinity,
                    // 预订部的高度
                    margin: const EdgeInsets.only(top: 0),
                    color: Colors.white,
                    padding: const EdgeInsets.all(16),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text(
                          '按院区筛选',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 8),
                        _buildHospitalFilterSection(),
                        const SizedBox(height: 20),
                        const Text(
                          '按级别筛选',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(height: 12),
                        _buildLevelFilterSection(),
                        const SizedBox(height: 16),
                        _buildActionButtons(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 构建院区筛选选项区域（单选）
  Widget _buildHospitalFilterSection() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children:
          _hospitalFilterOptions.map((option) {
            return Expanded(
              flex: 1, // 设置权重为1，使每个选项平均分布
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 4.0), // 添加水平间距
                child: _buildFilterChip(
                  option,
                  color: _filterColors[option] ?? Colors.blue,
                  isSelected: _selectedHospitalFilter == option,
                  onTap: () => _selectHospitalFilter(option),
                  showBadge: false,
                ),
              ),
            );
          }).toList(),
    );
  }

  /// 构建级别筛选选项区域（多选）
  Widget _buildLevelFilterSection() {
    // 将选项分成多行，每行3个选项
    final List<List<String>> rows = [];
    final List<String> options = _levelFilterSelections.keys.toList();

    for (int i = 0; i < options.length; i += 3) {
      final end = (i + 3 < options.length) ? i + 3 : options.length;
      rows.add(options.sublist(i, end));
    }

    return Column(
      children:
          rows.map((rowOptions) {
            return Padding(
              padding: const EdgeInsets.only(bottom: 10.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  ...rowOptions.map((option) {
                    return Expanded(
                      flex: 1, // 设置权重为1，使每个选项平均分布
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 4.0),
                        // 添加水平间距
                        child: _buildFilterChip(
                          option,
                          color: _filterColors[option] ?? Colors.blue,
                          isSelected: _levelFilterSelections[option] ?? false,
                          onTap: () => _toggleLevelFilterOption(option),
                          showBadge: true,
                        ),
                      ),
                    );
                  }),
                  // 添加空白占位组件，保持每行3个元素
                  ...List<Widget>.generate(
                    3 - rowOptions.length,
                    (_) => Expanded(
                      flex: 1, // 设置权重为1，与其他选项保持一致
                      child: Container(),
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
    );
  }

  /// 构建筛选选项
  Widget _buildFilterChip(
    String label, {
    required Color color,
    required bool isSelected,
    required VoidCallback onTap,
    required bool showBadge,
  }) {
    // 获取首字符作为标识
    String badgeText = '';
    if (showBadge) {
      badgeText = label.substring(0, 1);
    }

    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: double.infinity,
        alignment: Alignment.center,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          decoration: BoxDecoration(
            color: isSelected ? color.withOpacity(0.1) : Colors.grey[100],
            borderRadius: BorderRadius.circular(6),
            border: isSelected ? Border.all(color: color, width: 1) : null,
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              if (showBadge)
                Container(
                  width: 20,
                  height: 20,
                  decoration: BoxDecoration(
                    color: color, // 始终使用对应的颜色，不再根据选中状态变化
                    borderRadius: BorderRadius.circular(4),
                  ),
                  alignment: Alignment.center,
                  child: Text(
                    badgeText,
                    style: const TextStyle(
                      color: Colors.white,
                      fontSize: 12,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              if (showBadge) const SizedBox(width: 6),
              Flexible(
                child: Text(
                  label,
                  textAlign: TextAlign.center,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: isSelected ? color : Colors.black87,
                    fontSize: 13,
                    fontWeight:
                        isSelected ? FontWeight.w500 : FontWeight.normal,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建操作按钮
  Widget _buildActionButtons() {
    return Row(
      children: [
        // 取消按钮
        Expanded(
          child: Container(
            height: 44,
            margin: const EdgeInsets.only(right: 8),
            child: TextButton(
              onPressed: _closeDialog,
              style: TextButton.styleFrom(
                backgroundColor: Colors.grey[200],
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(22),
                ),
              ),
              child: const Text(
                '取消',
                style: TextStyle(color: Colors.black87, fontSize: 16),
              ),
            ),
          ),
        ),
        // 确认按钮
        Expanded(
          child: Container(
            height: 44,
            margin: const EdgeInsets.only(left: 8),
            child: ElevatedButton(
              onPressed: _confirmSelection,
              style: ElevatedButton.styleFrom(
                backgroundColor: AppTheme.primaryColor,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(22),
                ),
                elevation: 0,
              ),
              child: const Text('确认', style: TextStyle(fontSize: 16)),
            ),
          ),
        ),
      ],
    );
  }
}

// 1. 按级别筛选中的选项显示带颜色的首字符标识
//
// - 修改了 _buildFilterChip 方法，确保首字符标识始终使用对应的颜色，不再根据选中状态变化
// - 原来的代码在未选中状态下使用灰色，现在改为始终使用对应的颜色，与设计图一致
// 2. 每个选项设置权重为1，使它们平均分布
//
// - 在 _buildHospitalFilterSection 和 _buildLevelFilterSection 方法中，为每个选项的Expanded组件添加了 flex: 1 属性
// - 添加了 mainAxisAlignment: MainAxisAlignment.spaceEvenly 确保选项均匀分布
// - 设置了适当的水平间距 padding: const EdgeInsets.symmetric(horizontal: 4.0)
// 3. 按级别筛选的选中效果与按院区筛选一致
//
// - 两种筛选选项现在都使用相同的选中效果：背景色为对应颜色的淡色版本，边框为对应颜色
// 4. 修复了代码结构问题
//
// - 重写了整个文件，修复了重复的方法定义和多余的大括号问题
// - 确保代码结构清晰，没有冗余或错误的代码
// 这些修改使筛选对话框的视觉效果与设计图保持一致，同时改进了布局结构，使每个选项平均分布，提升了用户体验
